/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2015-02-09 14:36:36
 * @filename : static/site/nff/controller/emailCompose.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module) {
    require('{component}promptTip/promptTip.css');
    var ComposeView, nav='compose',emailType,emailName,eId, 
        mId = 'compose',reRender = true,ajaxTrue = true,menuName = 'compose',
        tpl = require('{view}emailCompose.tpl'),
        promptTip = require('{component}promptTip/promptTip'),
        panel = require('{component}panel/zepto.panel'),
        imglazyload = require('{component}imglazyload/zepto.imglazyload'),
        tplN = require('{view}userNav.tpl');

    ComposeView = Backbone.View.extend({

        el: '',

        template: _.template(tpl),
        templateN: _.template(tplN),

        initialize: function () {},

        render: function (objs) {
            if (!share.checkPermission(true)){return;};
            
            if (objs.val) {
                var obj = JSON.parse(objs.val);
                if (obj.type == 'addUser') {
                    share.reRender(false,mId);
                } else {
                    emailType = '',eId='';
                    share.reRender(reRender,mId);
                }
            } else {
                emailType = '',eId='';
                share.reRender(reRender,mId);
            }
            window.scroll(0,0);
            if ($('#'+mId).length < 1) { 
                $('body').append(this.template());
                this.bindEvt();            
            } else {
                $('#'+mId).css('display','block');
            }
            share.panel(panel,this.templateN,mId,menuName);

            if (objs.val) {
                emailType = obj.emailType;
                emailName = obj.emailName;
                if (obj.type == 'draft') {
                    eId = obj.eid;
                    this.getDraft({message_id:eId,subfolder:emailType}); 
                } else {
                    this.draftData({to:obj.userName});
                }
            }
        },

        getDraft : function(data) {
            var tthis = this;
            var obj = {
                url : seajs.data.vars.apiAccessUrl+'wm_display_email',
                type : 'POST',
                data : data,
                success : function(data) {
                    if (data.ret) {
                        tthis.draftData(data);
                    }
                },
                error : function(xhr, errorType, error) {},
                complete : function(xhr, status) {
                    share.pageLoad(false,$('body'));
                }
            };
            share.pageLoad(true,$('body'));
            $.ajax(share.ajaxControl(obj));
        },
      
        draftData : function(data) {
            var dom = $('#'+mId),
                username = data.to,
                subject = data.subject,
                text = data.content;

            if (username) {
                dom.find('.compose_name').find('input').val(username);              
            }
            if (subject) {
                dom.find('.compose_content').find('input').val(subject);              
            }
            if (text) {
                text = $.trim($('<p>'+text+'</p>').text());
                dom.find('.compose_content').find('textarea').val(text);              
            }
        },

        bindEvt : function() {
            var tthis = this,dom = $('#'+mId);    
 
            dom.find('.back').on('tap',function(e){
                e.stopPropagation();
                window.location.href = (emailType) ? '#emailList/whole/custom'+emailType+'##'+emailName : '#emailList/whole' ;
            }); 

            dom.find('.compose_add_user').on('tap',function(){
                window.location.href = '#composeUser/whole';
            });

            dom.find('.save').on('tap',function(){
                //check
                var obj = {};
                obj.to = $.trim(dom.find('.email_to').val());
                obj.subject = $.trim(dom.find('.email_subject').val());
                obj.txt  = dom.find('.email_txt').val();
                obj.subfolder = emailType;
                obj.send_cc_to_real_email = 0;
                obj.replied_msg_id = '';
                obj.del_draft_msg_id = eId;
                var bool = tthis.checkEmail(obj);
                if(bool) {
                    dom.find('.promptTip').html('');
                    tthis.checkUserName(obj);
                }
            });

        },

        checkEmail : function(obj) {
             var bool = true,
                 dom = $('#'+mId);   
        
             dom.find('.promptTip').html('');
 
             if (obj.to == ''){
                 bool = false;
                 promptTip.show({type:'error',text:'Please type a username.',dom:dom.find('.promptTip'),time:2000});
             }

             else if (obj.subject == '') {
                 bool = false;
                 promptTip.show({type:'error',text:'Please type a subject.',dom:dom.find('.promptTip'),time:2000});                   }

             else if (obj.txt == '') {
                 bool = false;
                 promptTip.show({type:'error',text:'Please type a message.',dom:dom.find('.promptTip'),time:2000});                   }
 
             return bool; 
        },
    
        checkUserName : function(dataObj) {
            var tthis = this, 
                dom = $('#'+mId);   
            var obj = {
                url : seajs.data.vars.apiAccessUrl+'wm_user_info',
                type : 'POST',
                data : 'user='+dataObj.to,
                success : function(data) {
                    if (data.usr_id > 0) {
                        tthis.sendEmail(dataObj); 
                    } else {
                        promptTip.show({type:'error',text:data.error, dom:dom.find('.promptTip')});
                        share.pageLoad(false,$('body'));
                    }
                },
                error : function(xhr, errorType, error) {
                },
                complete : function(xhr, status) {
                }
            };
            share.pageLoad(true,$('body'));
            $.ajax(share.ajaxControl(obj)); 
        }, 
 
        clearEmail : function() {
             var dom = $('#'+mId); 
             dom.find('.email_to').val('');
             dom.find('.email_subject').val('');
             dom.find('.email_txt').val('');
        },
 
        sendEmail : function(dataObj) {
            var tthis = this , dom = $('#'+mId).find('.body_all').find('ul');
            var obj = {
                url : seajs.data.vars.apiAccessUrl+'wm_send_email',
                type : 'POST',
                data : dataObj,
                success : function(data) {
                    if (data.ret) {
                        setTimeout(function(){
                           promptTip.show({type:'success',text:'Email successfully sent.',dom:$('#'+mId).find('.promptTip'),time:2000});                           
                           tthis.clearEmail();
                        },500);
                    } else {
                        if (data.errcode == 603) {
                            promptTip.show({type:'btn',btnText:'Upgrade',text:'Upgrade now to contact this member today.',dom:$('#'+mId).find('.promptTip'),callback:function(){
                                 tthis.saveDraft(dataObj);
                                 window.location.href = '#upgrade/whole';
                            }});
                        }
                    } 
                },
                error : function(xhr, errorType, error) {
                },
                complete : function(xhr, status) {
                    share.pageLoad(false,$('body'));
                    ajaxTrue = true;
                }
            };
            share.pageLoad(true,$('body'));
            if (ajaxTrue) {
                ajaxTrue = false;
                $.ajax(share.ajaxControl(obj)); 
            }
        },

        saveDraft : function(data) {
            var obj = {
                url : seajs.data.vars.apiAccessUrl+'wm_save_email',
                type : 'POST',
                data : data,
                success : function(data) {
                    if (data.ret) {
                    } 
                },
                error : function(xhr, errorType, error) {
                },
                complete : function(xhr, status) {
                }
            };
            $.ajax(share.ajaxControl(obj)); 
        },

    });
    module.exports = ComposeView;
});


